package com.itheima.stock.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @Description 公共数据库范围匹配逻辑
 */
public class CommonDbRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        //获取逻辑表
        String logicTableName = rangeShardingValue.getLogicTableName();
        //获取片键
        String columnName = rangeShardingValue.getColumnName();
        //获取封装上限和下限的对象
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        //判断是否有下限
        if (valueRange.hasLowerBound()) {
            //获取下限
            Date lowerEndpoint = valueRange.lowerEndpoint();
            //获取年份
            int startYear = new DateTime(lowerEndpoint).getYear();
            //获取出数据库名称后缀的值大于或者等于起始年的数据库名称集合
            collection = collection.stream().filter(dbName -> Integer.valueOf(dbName.substring(dbName.lastIndexOf("-") + 1)) >= startYear).collect(Collectors.toList());
        }
        //判断是否有上限
        if (valueRange.hasUpperBound()) {
            //获取上限
            Date upperEndpoint = valueRange.upperEndpoint();
            //获取年份
            int endYear = new DateTime(upperEndpoint).getYear();
            //获取出数据库名称后缀的值大于或者等于起始年的数据库名称集合
            collection = collection.stream().filter(dbName -> Integer.valueOf(dbName.substring(dbName.lastIndexOf("-") + 1)) <= endYear).collect(Collectors.toList());
        }
        return collection;
    }
}
